package com.zzyl.nursing.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author shangguanzhiyu
 * @date 2025-08-11
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 身份证号
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        // 床位ID
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        // 老人信息
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        // 合同信息
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        // 入住配置
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        // 家人信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        // 1.校验老人是否已入住
        // 个人写法
        /*Elder elder = getElder(idCardNo);
        // 1.1 已入住,结束流程,提示:老人已入住
        if (elder != null) {
            Integer status = elder.getStatus();
            if (status == 1 || status == 2 || status == 4) {
                // 已入住,结束流程,提示:老人已入住
                throw new BaseException("老人已入住");
            }
        }*/

        // 洋哥写法
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,idCardNo).in(Elder::getStatus,1,2,4);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (Objects.nonNull(elder)){
            throw new BaseException("老人已入住");
        }
        // 2.更新床位状态
        // 个人写法
        /*Bed bed = new Bed();
        bed.setId(bedId);
        bed.setBedStatus(1);
        int row = bedMapper.updateById(bed);*/

        // 洋哥写法
        Bed bed = bedMapper.selectById(bedId);
        bed.setBedStatus(1);
        int row = bedMapper.updateEnableStatusById(bed.getBedStatus(),bedId);
        if (row <= 0) {
            throw new BaseException("床位已入住");
        }
        // 3.新增或更新老人
        // 个人写法
        /* if (elder == null){
            // 新增
            elderMapper.insertElder(setElder(checkInElderDto));
        }else {
            // 更新
            elder.setStatus(1);
            elderMapper.updateElder(elder);
        }*/

        // 洋哥写法
        elder = insertOrUpdateElder(checkInElderDto,bed);
        // 4.新增签约办理
        /*contractMapper.insertContract(setContract(checkInContractDto));*/
        insertContract(elder,checkInConfigDto ,checkInContractDto);
        // 5.新增入住信息
        CheckIn checkIn = insertCheckId(elder,checkInConfigDto, elderFamilyDtoList);
        // 6.新增入住配置
        insertCheckInConfig(checkIn,checkInConfigDto);
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        CheckInConfigVo checkInConfigVo;
        // 获得入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        // 根据id查询老人信息
        if (ObjectUtils.isEmpty(checkIn)){
            throw new BaseException("入住信息不存在");
        }
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        if (ObjectUtils.isNotEmpty(checkIn.getElderId())){

        }
        BeanUtils.copyProperties(elder,checkInElderVo);
        // 查询最新的合同信息
        Contract contract = contractMapper.selectContractByElderId(checkIn.getElderId());
        // 查询入住新配置
        checkInConfigVo = checkInConfigMapper.selectCheckInConfigByCheckInId(id);
        // 转换家属列表
        List<ElderFamilyVo> elderFamilyVo = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        // 整合数据返回
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    /** 新增入住信息 */
    private CheckIn insertCheckId(Elder elder, CheckInConfigDto checkInConfigDto, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(elder,checkIn,"id");
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /** 新增入住配置信息 */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto){
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /** 封装签约办理信息-个人写法  */
    private Contract setContract(CheckInContractDto checkInContractDto) {
        Contract contract = new Contract();
        // 合同名称
        contract.setContractName(checkInContractDto.getContractName());
        // 签约时间
        contract.setSignDate(checkInContractDto.getSignDate());
        // 丙方名称
        contract.setThirdPartyName(checkInContractDto.getThirdPartyName());
        // 丙方手机号
        contract.setThirdPartyPhone(checkInContractDto.getThirdPartyPhone());
        // 合同pdf文件地址
        contract.setAgreementPath(checkInContractDto.getAgreementPath());

        return contract;
    }


    /** 设置老人信息-个人写法 */
    private Elder setElder(CheckInElderDto checkInElderDto) {
        Elder elder = new Elder();
        // 姓名
        elder.setName(checkInElderDto.getName());
        // 身份证号
        elder.setIdCardNo(checkInElderDto.getIdCardNo());
        // 出生日期
        elder.setBirthday(checkInElderDto.getBirthday());
        // 性别
        elder.setSex(checkInElderDto.getSex());
        // 手机号
        elder.setPhone(checkInElderDto.getPhone());
        // 家庭地址
        elder.setAddress(checkInElderDto.getAddress());
        // 一寸照片
        elder.setImage(checkInElderDto.getImage());
        // 身份证国徽面
        elder.setIdCardNationalEmblemImg(checkInElderDto.getIdCardNationalEmblemImg());
        // 身份证人像面
        elder.setIdCardPortraitImg(checkInElderDto.getIdCardPortraitImg());
        // 设置默认状态为入住中
        elder.setStatus(1);
        return elder;
    }

    /**
     * 获取老人信息
     */
    private Elder getElder(String idCardNo) {
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        return elderMapper.selectOne(elderWrapper.eq(Elder::getIdCardNo, idCardNo));
    }
    /** 新增签约办理-洋哥 */
    private void insertContract(Elder elder, CheckInConfigDto checkInConfigDto, CheckInContractDto checkInContractDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(0);
        contractMapper.insert(contract);
    }

    /** 新增或更新老人-洋哥 */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto,Bed bed){
        // 准备老人的数据
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        elderWrapper.eq(Elder::getIdCardNo,elder.getIdCardNo());
        Elder elderDb = elderMapper.selectOne(elderWrapper);
        if (Objects.isNull(elderDb)){
            // 新增
            elderMapper.insert(elder);
        }else {
            // 更新
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }
}
